//请求函数
import { reqCartList, reqUpdateCartChecked,reqDeleteCart} from "@/api";
import { getUserId } from "@/utils/USER_UUID";
//购物车小仓库地方
const state = {
    //存储用户临时身份【唯一、持久化】
    USER_ID: getUserId(),
    //用户购物车的数据
    shopList: []
};
const mutations = {
    GETCARTLIST: (state, shopList) => {
        state.shopList = shopList;
    }
}
const actions = {
    //getCartList类型的action-----获取购物车列表
    getCartList: async ({ commit, state, dispatch }) => {
        //获取到购物车的数据
        let result = await reqCartList();
        if (result.code == 200) {
            //提交mutation，存储用户购物车数据
            commit("GETCARTLIST", result.data);
        }

    },
    //updateChecked类型的action(修改某一个商品的状态)
    updateChecked: async({ commit, state, dispatch }, { skuId, isChecked }) => {
        //skuId,商品的skuId isChecked:0未勾选 1勾选
        let result = await reqUpdateCartChecked(skuId, isChecked);
        if(result.code==200){
            return 'ok';
        }else{
           return Promise.reject();  
        }
    },
    //deleteCart类型的action(删除某一个商品)
    deleteCart:async ({commit,state,dispatch},skuId)=>{
            let result  = await reqDeleteCart(skuId);
            //判断删除成功与失败
            if(result.code==200){
                 return "ok";
            }else{
                return Promise.reject();
            }
    },
    //修改全部商品
    updateAllChecked:({commit,state,dispatch},isChecked)=>{
        let all = [];
        //遍历购物车数组
        state.shopList[0].cartInfoList.forEach((item)=>{
            //调用修改某一个商品action
            let promise = dispatch('updateChecked',{skuId:item.skuId,isChecked});
            all.push(promise);
        });
        return Promise.all(all);
    },
    deleteCartByChecked:({getters,commit,state,dispatch})=>{
        let arr = [];
        //getters\state都可以后去仓库数据
        state.shopList[0].cartInfoList.forEach(item=>{
            //购物车里只有被勾选的商品才会被删除
            if (item.isChecked==1) {
                let promise = dispatch('deleteCart',item.skuId)
                arr.push(promise)
            }
        })
        //返回promise
        return Promise.all(arr);
    }
};
const getters = {
    //简化购物车的数据
    shopCartList(state) {
        return state.shopList[0] || {};
    }
};

//默认暴露:小仓库对外暴露的是对象,默认暴露
export default {
    state,
    mutations,
    actions,
    getters
}